package com.zjitc.controller;

import com.ems.KdApiOrderDistinguish;
import com.ems.KdniaoTrackQueryAPI;
import com.google.gson.Gson;
import com.zjitc.common.PageModel;
import com.zjitc.pojo.exp.Disting;
import com.zjitc.pojo.exp.ExpResult;
import com.zjitc.pojo.exp.Shipper;
import com.zjitc.pojo.Express;
import com.zjitc.common.ServerResponse;
import com.zjitc.pojo.Caritem;
import com.zjitc.pojo.Orders;
import com.zjitc.pojo.User;
import com.zjitc.service.CarService;
import com.zjitc.service.ExpressService;
import com.zjitc.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * Create By IntelliJ IDEA
 *
 * @author:
 * @create-Time: 2017/11/23  11:47
 */
@Controller
@RequestMapping("/order")
public class OrderController {

  private final OrderService service;
  private final CarService carService;
  private final ExpressService Eservice;
  private final String USER = "user";

  @Autowired
  public OrderController(CarService carService,
      OrderService service, ExpressService eservice) {this.carService = carService;

    this.service = service;
    this.Eservice = eservice;
  }

  /**
   * 跳转到 order_info
   */
  @RequestMapping("/addOrder")
  @ResponseBody
  public ServerResponse orderinfo(HttpSession session)
      throws ServletException, IOException, InterruptedException {
    User user = (User) session.getAttribute(USER);
    List<Caritem> caritems = carService.findAll(user.getUid());

    if (carService.findAll(user.getUid()) != null) {
      carService.deleteAll(user.getUid());
    }
    return service.addorder(user, caritems);
  }

  /**
   * 跳转到 order_list
   */
  @RequestMapping("/orderlist")
  public ModelAndView list(HttpSession session,
      @RequestParam(value = "pageid", required = false, defaultValue = "0") Integer pageid)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    User user = (User) session.getAttribute(USER);
    PageModel<Orders> orders = service.findPageByUid(user.getUid(), pageid);
    String page = "page";
    modelAndView.addObject(page, orders);
    modelAndView.setViewName("order_list");
    return modelAndView;
  }

  /**
   * ########## 点击付款后————跳转到 order_info
   */
  @RequestMapping("/orderPay")
  public ModelAndView orderpay(String oid, HttpSession session)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    User user = (User) session.getAttribute(USER);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    String order1 = "order";
    modelAndView.addObject(order1, order);
    modelAndView.setViewName("order_info");
    return modelAndView;
  }

  @RequestMapping("/createOrder")
  @ResponseBody
  public ServerResponse orderpayByOrder(@RequestParam("pid") String pid,
      @RequestParam("count") String count, HttpSession session) {
    User user = (User) session.getAttribute(USER);
    List<Caritem> caritems = service.createOrderitem(pid, count);
    boolean b = service.hasinventory(pid, count);
    if (!b) {
      return ServerResponse.createError();
    }
    Orders orders = service.createOrder(caritems, user);
    return ServerResponse.createSuccess(orders);
  }

  @RequestMapping("gotoOrderInfo")
  public String gotoOrderInfo(@RequestParam("order") Orders orders,RedirectAttributes attributes){
    attributes.addAttribute("order",orders);
    return "order_info";
  }

  /**
   * ################ order_info点击确认订单后跳转到支付界面
   */
  @RequestMapping("/CompleteOrder")
  public ModelAndView complete(
      @RequestParam("oid") String oid,
      @RequestParam("address") String address,
      @RequestParam("username") String username,
      HttpSession session)
      throws ServletException, IOException, SQLException {
    try {
      service.judgeandupdate(session);
    } catch (TimeoutException e) {
      e.printStackTrace();
    }
    User user = (User) session.getAttribute(USER);
    ModelAndView modelAndView = new ModelAndView();
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    order.setAddress(address);
    order.setName(username);
    order.setAddress(address);
    service.update(user, order);
    String outTradeNo = order.getOid();
    String totalamount = String.valueOf(order.getTotal());
    //总价
    String tantamount = "total_amount";
    modelAndView.addObject(tantamount, totalamount);
    //订单编号
    String outdrawn = "out_trade_no";
    modelAndView.addObject(outdrawn, outTradeNo);
    modelAndView.setViewName("alipay.trade.page.pay");
    return modelAndView;
  }

  /**
   * ################### 支付完成后跳转回order_list
   */
  @RequestMapping("/completePay")
  public ModelAndView completepay(
      @RequestParam("out_trade_no") String oid,
      @RequestParam("trade_no") String tradeno,
      HttpSession session
  ) throws SQLException, IOException {
    User user = (User) session.getAttribute(USER);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    order.setState(1);
    order.setTradeno(tradeno);
    //修改orders数据库
    service.update(user, order);
    String pay = "pay";
    service.updateinventory(order.getOrderitems(), pay);
    try {
      Eservice.add(oid);
    } catch (Exception e) {
      e.printStackTrace();
    }
    ModelAndView m = new ModelAndView();
    m.setViewName("redirect:/order/orderlist.do");
    return m;
  }

  /**
   * 删除订单
   */
  @RequestMapping("/orderDelete")
  @ResponseBody
  public ServerResponse delete(String oid, HttpSession session)
      throws ServletException, IOException {
    User user = (User) session.getAttribute(USER);
    return service.deleteorder(user.getUid(), oid);
  }

  /**
   * 取消订单/退款
   */
  @RequestMapping("/orderCancel")
  public ModelAndView cancel(
      @RequestParam(value = "WIDTRout_trade_no") String outtradeno,
      @RequestParam(value = "WIDTRrefund_amount") String refundamount,
      @RequestParam(value = "WIDTRrefund_reason") String refundreason
  ) throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("WIDTRout_trade_no", outtradeno);
    modelAndView.addObject("WIDTRrefund_amount", refundamount);
    modelAndView.addObject("WIDTRrefund_reason", refundreason);
    modelAndView.setViewName("/alipay.trade.refund");
    return modelAndView;
  }

  @RequestMapping("shipments")
  public String shipments(String oid) {
    service.shipments(oid);
    return "redirect:/admin/adminFindAllOrder.do";
  }

  @RequestMapping("expcheck")
  public ModelAndView expcheck(String oid, HttpSession session) throws Exception {
    User user = (User) session.getAttribute(USER);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    Express check = Eservice.check(oid);
    //单号查询
    KdApiOrderDistinguish kda = new KdApiOrderDistinguish();
    String codejson = kda.getOrderTracesByJson(check.getCode());
    Gson gson = new Gson();
    Disting disting = gson.fromJson(codejson, Disting.class);
    List<Shipper> shippers = disting.getShippers();
    String expCode = "";
    Shipper shipper = null;
    for (Shipper s : shippers) {
      shipper = new Shipper(s.getShipperCode(), s.getShipperName());
    }
    expCode = shipper.getShipperCode();
    //快递即时查询
    KdniaoTrackQueryAPI kdn = new KdniaoTrackQueryAPI();
    String result = kdn.getOrderTracesByJson(expCode, check.getCode());
    ExpResult expResult = gson.fromJson(result, ExpResult.class);
    ModelAndView modelAndView = new ModelAndView("expecheck");
    modelAndView.addObject("result", expResult);
    modelAndView.addObject("shipper", shipper);
    modelAndView.addObject("check", check);
    modelAndView.addObject("order", order);
    return modelAndView;
  }

  @RequestMapping("confirm")
  public String confirm(String oid, HttpSession session) {
    User user = (User) session.getAttribute(USER);
    service.confirm(user, oid);
    return "redirect:/order/orderlist.do";
  }

  /**
   * 退款   完成
   */
  @RequestMapping("/refund")
  public ModelAndView refund(
      String msg, @RequestParam("WIDTRout_trade_no") String oid, HttpSession session)
      throws SQLException, ServletException, IOException {
    String success = "Success";
    User user = (User) session.getAttribute(USER);
    if (success.equals(msg)) {
      Orders order = service.findOrderFromRedis(user.getUid(), oid);
      order.setState(4);
      service.update(user, order);
      String refund = "refund";
      service.updateinventory(order.getOrderitems(), refund);
      msg = "退款成功";
    } else {
      msg = "退款失败";
    }
    ModelAndView modelAndView = new ModelAndView("refund");
    modelAndView.addObject("msg", msg);
    return modelAndView;
  }

}
